/**
 * @(#)MainActivity.java 1.0 2013/9/17
 * Copyright 2013 PD, Inc. All rights reserved.
 */
package cn.broadin.app.hotel.startWebapp;

import cn.broadin.app.hotel.R;
import cn.broadin.app.hotel.bz.BasePDBiz;
import cn.broadin.app.hotel.factory.PDBizFactory;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder.Callback;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.RelativeLayout;


import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class StartWebView extends Activity implements OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
SurfaceHolder.Callback {
	private static final String TAG = "StartWebView";		//log tag
	private WebView webView;								//webview对象
	private RelativeLayout llMainPage;						//linerLayout控件
	private static Activity ctx = null;							//当前Activity对象
	private BasePDBiz pdBiz = null;				            //pd通用接口
	public static Handler mHandler = null;					//定义handler，供其它页面调用
	private static MediaPlayer mMediaPlayer;
	private static SurfaceView mPreview;
	private static SurfaceHolder holder;
	private static Callback webViewCallBack;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_page);
		ctx = this;
		Bundle extras = getIntent().getExtras();
		String url = extras.getString("url");
		String dataHost = extras.getString("data_host");
		String dataPort = extras.getString("data_port");
		Log.d("dyhstartWebView:","url = " + url + " data_host = " + dataHost + " data_port = "+ dataPort);
		initView(url,dataHost,dataPort);
		if (url.indexOf("test.htm") != -1 || url.indexOf("hotel_intro/index.htm") != -1) {
			initSurfaceView();
		}
	}
	
	/**
	 * 初始化视图
	 */
	@SuppressLint({ "HandlerLeak", "NewApi" })
	private void initView(String url, String dataHost, String dataPort) {
		webView = new WebView(ctx);
		llMainPage = (RelativeLayout)findViewById(R.id.ll_mainPage);
		llMainPage.addView(webView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		webView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);  
		webView.setBackgroundColor(0);
		//pd逻辑处理
		pdBiz = PDBizFactory.getPDBiz(this, webView);
		pdBiz.setWebViewInfo(url,dataHost,dataPort);
		//创建Handler
		mHandler = new Handler(){
			@Override
			public void dispatchMessage(Message msg) {
				switch(msg.what){
				case 0:			//音频播放完毕发送消息事件
					Log.d("caolm:","javascript:grabEvent(5404)");
					webView.loadUrl("javascript:grabEvent(5404)");
					break;
				}
			}
		};
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		pdBiz.grabEvent(event);
		return true;
	}	
	
	public void initSurfaceView() {
		Log.d("caolm:---------->","initSurfaceView");
		 mPreview = (SurfaceView) findViewById(R.id.surfaceView1);
		 mPreview.setVisibility(View.VISIBLE);
		 webViewCallBack = this;
		 holder = mPreview.getHolder();
		 holder.addCallback(webViewCallBack);
		 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	public static void playVideo(String videoUrl) {
		clean();
		try {
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setDataSource(videoUrl);
			mMediaPlayer.setDisplay(holder);
			mMediaPlayer.prepareAsync();
			mMediaPlayer.setOnCompletionListener((OnCompletionListener) ctx);
			mMediaPlayer.setOnPreparedListener((OnPreparedListener) ctx);
			mMediaPlayer.setOnVideoSizeChangedListener((OnVideoSizeChangedListener) ctx);
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mMediaPlayer.setVolume(1.0f, 1.0f);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void onCompletion(MediaPlayer arg0) {
		Log.d("caolm:media----->", "onCompletion");
	}


	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		Log.i("caolm:media----->", "onVideoSizeChanged");
		if (width == 0 || height == 0) {
			Log.e("caolm:media----->", "invalid video width(" + width + ") or height(" + height
					+ ")");
			return;
		}
		// if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
		startVideoPlayback();
		// }
	}
	
	public void onPrepared(MediaPlayer mediaplayer) {
		Log.i("caolm:media----->", "onPrepared");
		// if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
		startVideoPlayback();
		// }
	}

	public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
		Log.i("caolm:media----->", "surfaceChanged");
	}

	public void surfaceDestroyed(SurfaceHolder surfaceholder) {
		Log.i("caolm:media----->", "surfaceDestroyed");
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.i("caolm:media----->", "surfaceCreated");
		//playVideo();
	}
	
	public static void releaseMediaPlayer() {
		if (mMediaPlayer != null) {
			// mMediaPlayer.stop();
			Log.d("caolm:","releaseMediaPlayer");
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}


	private static void clean() {

	}

	private void startVideoPlayback() {
		Log.i("caolm:media----->", "startVideoPlayback");
		// holder.setFixedSize(mVideoWidth, mVideoHeight);
		mMediaPlayer.start();
	}

	@Override
	protected void onPause() {
		//releaseMediaPlayer();
		//clean();
		releaseMediaPlayer();
		super.onPause();
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 停止服务
		releaseMediaPlayer();
		//clean();
	}
	
	@Override
	protected void onStop() {
		Log.i(TAG, "activity stoped.");
		super.onStop();
		//finish();
		//System.exit(0);
		releaseMediaPlayer();
		//clean();
	}
}